package com.cc.service.generate;


import cn.hutool.core.collection.CollectionUtil;
import com.cc.build.BuiderDb;
import com.cc.config.PackagePathConfiguration;
import com.cc.config.TemplateConfiguration;
import com.cc.pojo.bo.TransBo;
import com.cc.pojo.file.BuiderAbstract;
import com.cc.pojo.file.FilePathAndClassName;
import com.cc.pojo.tablestruct.LibaryProperties;
import com.cc.pojo.tablestruct.TableStruct;
import com.cc.service.core.GenerateAbstract;
import com.cc.utils.beanUtil.BeanUtils;
import com.cc.utils.ConvertHumpUnderlinesToEachOtherUtil;
import com.cc.utils.CoreUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author c.c
 * @Description 核心生成类
 * @since 2023/3/30
 */
@Slf4j
public class GenerateDb extends GenerateAbstract {

  private PackagePathConfiguration packagePathConfiguration = BeanUtils.getBean(PackagePathConfiguration.class);
  private TemplateConfiguration templateConfiguration = BeanUtils.getBean(TemplateConfiguration.class);

  public GenerateDb() {
    this.getTargetPackageAddress();
  }

  @Override
  public List<FilePathAndClassName<BuiderAbstract>> getTargetPackageAddress(Object... youParameter) {

    List<LibaryProperties> libaryProperties = super.getLibaryProperties();
    List<FilePathAndClassName<BuiderAbstract>> packageAddress = new ArrayList<>();
    libaryProperties.forEach(libaryProperty -> {
      StringBuilder packgePath = new StringBuilder();
      //获取输出路径
      CoreUtil.getPath(libaryProperty, packgePath, packagePathConfiguration.isDbisLastLayer(), packagePathConfiguration.getDbPath());
      //获取类名
      String classname = ConvertHumpUnderlinesToEachOtherUtil.underlineToHump(libaryProperty.getTableName(), true) + "Db";
      //获取生成类
      if (CollectionUtil.isNotEmpty(libaryProperty.getTableStructs())) {
        List<TransBo> transBos = libaryProperty.getTableStructs()
          .stream()
          .map(TableStruct::convertBuiderDbDtoByTableStruct)
          .collect(Collectors.toList());
        BuiderDb buiderDb = new BuiderDb(packgePath.toString(),
          classname,
          libaryProperty.getTableName(),
          transBos
        );
        super.putPathAddress(classname, packgePath);
        //转换路径并封装为一个类
        FilePathAndClassName<BuiderAbstract> filePathAndClassName = new FilePathAndClassName<>(packgePath.toString(), classname, buiderDb);
        packageAddress.add(filePathAndClassName);
      } else {
        log.info("表" + libaryProperty.getTableName() + "中tableStructs数据为空");
//        throw new RuntimeException("表"+libaryProperty.getTableName()+"中tableStructs数据为空");
      }
    });
    super.build(packageAddress, templateConfiguration.getDbPath());
    return packageAddress;
  }
}
